package com.yun.zf.system.security.handle;

import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.yun.zf.common.admin.domain.LoginUser;
import com.yun.zf.common.constant.Constants;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.security.service.TokenService;
import com.yun.zf.system.security.token.WxAppletAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class WxAppletAuthenticationnSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 使用jwt管理，所以封装用户信息生成jwt响应给前端

       LoginUser user =((WxAppletAuthenticationToken)authentication).getUser();
        String token =  tokenService.createToken(user);
        Map<String, Object> result = Maps.newHashMap();
        result.put(Constants.TOKEN, token);
        result.put("openId",user.getOpendId());
        result.put("sessionKey",((WxAppletAuthenticationToken) authentication).getSessionKey());
        Response r = new Response(200,"登录成功",result);
        httpServletResponse.setContentType(ContentType.JSON.toString());
        httpServletResponse.getWriter().write(JSON.toJSONString(r));
    }
}
